package faf.business.tests;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import javax.persistence.EntityManager;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import faf.business.AdministrationManager;
import faf.dao.JpaUtils;
import faf.entities.Account;

public class AdministrationManagerTests {
	
	static JpaUtils jpautils;
	static AdministrationManager manager;
	
	@BeforeClass
	public static void beforeClass() {
		HashMap<String, String> config = new HashMap<String, String>();
		config.put("hibernate.hbm2ddl.auto", "create-drop");
		jpautils = new JpaUtils(config);
		manager = new AdministrationManager();
		manager.setJpautils(jpautils);
	}
	
	@Test
	public void listAccountsTest() {
		EntityManager em = jpautils.createEntityManger();
		Assert.assertEquals(0, manager.listAccounts().size());
		
		Account account = new Account();
		account.setFirstname("test");
		account.setLastname("test");
		account.setAdministrator(false);
		account.setMail("test@example.net");
		account.setRedactor(false);
		
		em.getTransaction().begin();
		em.persist(account);
		em.getTransaction().commit();
		Assert.assertEquals(1, manager.listAccounts().size());
		
		Account account2 = new Account();
		account2.setFirstname("test 2");
		account2.setLastname("test");
		account2.setAdministrator(false);
		account2.setMail("test@example.net");
		account2.setRedactor(false);
		
		em.getTransaction().begin();
		em.persist(account2);
		em.getTransaction().commit();
		
		Assert.assertEquals(2, manager.listAccounts().size());
		
		em.getTransaction().begin();
		em.remove(account);
		em.remove(account2);
		em.getTransaction().commit();
		
		Assert.assertEquals(0, manager.listAccounts().size());
		em.close();
	}
	
	@Test
	public void grantRedactorPrivilegeTest() {
		EntityManager em = jpautils.createEntityManger();
		
		Account account = new Account();
		account.setFirstname("test");
		account.setLastname("test");
		account.setAdministrator(false);
		account.setMail("test@example.net");
		account.setRedactor(false);
		
		em.getTransaction().begin();
		em.persist(account);
		em.getTransaction().commit();
		em.close();
		
		manager.grantRedactorPrivilege(account.getId());
		
		em = jpautils.createEntityManger();
		account = em.find(Account.class, account.getId());
		
		Assert.assertTrue(account.isRedactor());
		
		
		em.getTransaction().begin();
		em.remove(account);
		em.getTransaction().commit();
		em.close();
	}
}
